import _ from "lodash";
import { typeClassName } from "@/pages/config/classNameMap";
const requireComponent = require.context("./", true, /[A-Z]\w+\.(vue)$/);
const comp = {};
requireComponent.keys().forEach((fileName) => {
  if (fileName != "./index.vue") {
    const componentConfig = requireComponent(fileName);
    const name = componentConfig.default.name;
    const componentName = _.upperFirst(
      _.camelCase(
        name
          .split("/")
          .pop()
          .replace(/\.\w+$/, "")
      )
    );
    comp[componentName] = componentConfig.default || componentConfig;
  }
});
Object.keys(comp).map((key) => {
  comp[key].components = comp;
});
export default {
  components: comp,
  data() {
    return {
      vms: {}, //页面组件vue实例
      models: {
        //模型
        storehouseConfig: {
          ...typeClassName["storehouseConfig"],
        },
        team: {
          ...typeClassName["team"],
        },
        person: {
          ...typeClassName["person"],
        },
        tank: {
          ...typeClassName["tank"],
        },
      },
      parentId: "",
      teamData: [],
      personData: [],

      dataSet: {
        //数据集
        storeData: null, //所有仓库数据
        // storehouseData: [], //仓库数据
        storehouseFormData: {}, //仓库库位数据
        storeLocationFormData: {}, // 库位表单数据
        // storePositionCurrentData: {}, // 库位当前数据
        // tankTableData: [], // 桶数据
        // tankCurrentData: {},
      },
    };
  },
  provide() {
    return {
      anc: this,
    };
  },
  computed: {
    // filterEquipTypeOptions() {
    //   return this.equipTypeOptions.filter((d) => d.category === "1");
    // },
  },
  watch: {},
  created() {
    Object.keys(this.models).map((k) => {
      this.models[k].clz = this.$modelObject.create(this.models[k].modelType);
      this.models[k].clzs = this.$modelObject.create(
        this.models[k].modelType + "Collection"
      );
    });
  },
  mounted() {
    this.$nextTick(() => {
      this.loadPage();
      this.getTeam();
      this.getPerson();
      if (process.env.NODE_ENV === "development") {
        console.log(this);
      }
    });
  },
  methods: {
    /****************仓库操作 *******************************/
    /**
     * 页面加载方法
     */
    loadPage() {
      let filter = this._getModelFields(
        "storehouseConfig",
        "className",
        "type"
      );
      this.models.storehouseConfig.clz.query(filter).then((res) => {
        this.dataSet.storeData = this._getModelRecord("storehouseConfig");
      });
    },
    /**
     * 点击仓库创建按钮
     */
    handleCreate() {
      this._setVmValue("createModal", "config.show", true);
      this.dataSet.storehouseFormData = this.$modelObject.getTpl(
        this.models.storehouseConfig.modelType
      ); // 这是一个整理接口数据JSON格式的方法
    },
    /**
     * 创建仓库
     */
    createModalOk(btn) {
      this._$validateAll([this.vms.createView], (valid) => {
        if (valid) {
          this._merge(
            this.dataSet.storehouseFormData,
            this._getModelFields(
              "storehouseConfig",
              "className",
              "type",
            ),
            {
              containerModel: this.models.storehouseConfig.modelType,
              containerId: this.models.storehouseConfig.clz.record.id,
              parentId: 'root',
              values: {},
            }
          );
          this.$api.storehouse
            .addStorehouse(this.dataSet.storehouseFormData)
            .then((flag) => {
              this._setVmValue("createModal", "config.show", false);
              btn.loading = false;
              this.loadPage();
            });
        } else {
          btn.loading = false;
          this.$Message.info("请填写必填内容");
        }
      });
    },
    /**
     * @param {*} row
     * 编辑仓库
     */
    handleEdit(row) {
      this.dataSet.storehouseFormData = row;
      this._setVmValue("editModal", "config.show", true);
    },
    /**
     * 修改仓库
     */
    editModalOk(btn) {
      this._$validateAll([this.vms.editView], (valid) => {
        if (valid) {
          this._merge(this.dataSet.storehouseFormData, 
            this._getModelFields(
              "storehouseConfig",
              "className",
              "type",
            ),
            {
            containerModel: this.models.storehouseConfig.modelType,
            containerId: this.models.storehouseConfig.clz.record.id,
          });
          this.$api.storehouse
            .updateStorehouse(this.dataSet.storehouseFormData)
            .then((flag) => {
              this.$Message.success("修改成功");
              this._setVmValue("editModal", "config.show", false);
              btn.loading = false;
              this.loadPage();
            });
        } else {
          this.$Message.info("请填写必填内容");
        }
      });
    },
    /**
     * @param {行数据} row
     * 仓库删除
     */
    handleDelete(row) {
      this._$deleteConfirm(() => {
        this.$api.storehouse.deleteStorehouse(row).then((flag) => {
          this.loadPage();
        });
      });
    },
    /*****************库位操作********************/
    /**
     *
     * @param {库位数据} ele
     */
    handleStoreEdit(ele) {
      this.dataSet.storeLocationFormData = ele;
      this._setVmValue("editLocationModal", "config.show", true);
    },
    /**
     * 库位编辑提交
     */
    editStoreModalOk(btn) {
      this._$validateAll([this.vms.editLocationView], (valid) => {
        this._merge(this.dataSet.storeLocationFormData, 
          this._getModelFields(
            "storehouseConfig",
            "className",
            "type",
          ),
          {
          containerModel: this.models.storehouseConfig.modelType,
          containerId: this.models.storehouseConfig.clz.record.id,
        });
        this.$api
          .HierInstanceSaveHier([this.dataSet.storeLocationFormData])
          .then((flag) => {
            this.$Message.success("修改成功");
            this._setVmValue("editLocationModal", "config.show", false);
            btn.loading=false;
            this.loadPage();
          });
      });
    },
    /********************************************************/
    tankQueryByPage(pageNavigation, filter) {
      filter = this._merge(filter, {
        className: this.models.tank.className,
        type: this.models.tank.type,
      });
      let data = {
        pageNumber: pageNavigation.pageNumber,
        pageSize: pageNavigation.pageSize,
        condition: this._$setFilteStr(filter),
      };
      this.$api.storehouse.queryTankNotLinkByPage(data).then((res) => {
        let tableData = this._clone(res.records);
        this.dataSet.tankTableData = tableData.map((item) => {
          return {
            ...item,
            ...item.values,
          };
        });
        this.vms.tankTable.pageNavigation.total = res.recordCount;
        this.vms.tankTable.loading = false;
        // // 整理数据 数据格式
        // this.dataSet.tableData = this.models["salesOrder"].clzs.valueRecords;
      });
    },
    /**
     * 获取组数据
     */
    getTeam() {
      let filter = {
        className: this.models.team.className,
        type: this.models.team.type,
      };
      this.models.team.clzs.query(filter).then((flag) => {
        if (flag) {
          this.teamData = this.models.team.clzs.records.map((item) => {
            return {
              label: item.values.sf_name,
              value: String(item.id),
            };
          });
        }
      });
    },
    /**
     * 获取人员数据
     */
    getPerson() {
      let filter = {
        className: this.models.person.className,
        type: this.models.person.type,
      };
      this.models.person.clzs.query(filter).then((flag) => {
        if (flag) {
          this.personData = this.models.person.clzs.records.map((item) => {
            return {
              label: item.values.sf_name,
              value: item.id,
            };
          });
        }
      });
    },

    /**
     *
     * @param {*} row
     *
     */
    handleDetail(row) {
      this.vms.detailModal.show = true;
      this.dataSet.storehouseFormData = row;
      this.onlyRead = true;
    },

    /**
     * 点击入库
     * @param {库位数据} ele
     * @param {仓库索引} index
     * @param {库位索引} keys
     */
    // handleStoreEnter(ele, index, keys) {
    //   if (ele.link.linkId != null) {
    //     this.$Message.error("该库位已绑定桶，请先解绑桶");
    //     return;
    //   }
    //   this.vms.tankTable.pageNavigation.pageNumber = 1;
    //   this.tankQueryByPage(this.vms.tankTable.pageNavigation, {});
    //   this.dataSet.storePositionCurrentData = ele;
    //   this.vms.tankModal.show = true;
    // },
    /**
     * 点击桶行数据
     * @param {行数据} row
     */
    // handlleTankTableRowClick(row) {
    //   this.dataSet.tankCurrentData = row;
    // },
    /**
     * 入库提交
     */
    // editSTankModalOk() {
    //   this._merge(this.dataSet.storePositionCurrentData, {
    //     className: this.models.storehouseConfig.className,
    //     type: this.models.storehouseConfig.type,
    //     containerModel: this.models.storehouseConfig.modelType,
    //     containerId: this.models.storehouseConfig.clz.record.id,
    //     linkId: this.dataSet.tankCurrentData.id,
    //   });

    //   this.$api.storehouse
    //     .inputBound(this.dataSet.storePositionCurrentData)
    //     .then((flag) => {
    //       this.vms.tankModal.show = false;
    //       this.$Message.success("入库成功");
    //       this.loadPage();
    //       this.dataSet.storePositionCurrentData = {};
    //     });
    // },
    /**
     * 点击出库
     * @param {库位数据} ele
     * @param {仓库索引} index
     * @param {库位索引} keys
     */
    // handleStoreOut(ele, index, keys) {
    //   console.log(ele);
    //   this.dataSet.storePositionCurrentData = ele;
    //   this._merge(this.dataSet.storePositionCurrentData, {
    //     className: this.models.storehouseConfig.className,
    //     type: this.models.storehouseConfig.type,
    //     containerModel: this.models.storehouseConfig.modelType,
    //     containerId: this.models.storehouseConfig.clz.record.id,
    //     linkId: this.dataSet.tankCurrentData.id,
    //   });
    //   if (ele.link.linkId == null) {
    //     this.$Message.error("该库位未绑定桶，请先绑桶");
    //     return;
    //   }
    //   this.$api.storehouse
    //     .outBound(this.dataSet.storePositionCurrentData)
    //     .then((flag) => {
    //       this.vms.tankModal.show = false;
    //       this.$Message.success("出库成功");
    //       this.loadPage();
    //       this.dataSet.storePositionCurrentData = {};
    //     });
    // },
    
    /****************工具***************/
    _getModelFields(name, ...args) {
      let map = {};
      args.map((key) => {
        map[key] = this.models[name][key];
      });
      return map;
    },
    _getModelRecord(name) {
      return this.models[name].clz.record;
    },
    _setVmValue(name, key, value) {
      _.set(this.vms[name], key, value);
    },
    _getModelTpl(name){
      return this.$modelObject.getTpl(this.models[name].modelType);
    },
    _setDataSet(name, data) {
      this.dataSet[name] = data;
    },
    _modalShow(name){
      _.set(this.vms[name], 'config.show', true);
    },
    _modalClose(name){
      _.set(this.vms[name], 'config.show', false);
      _.set(this.vms[name], 'config.loading', false);
    },
    _tableLoading(name){
      _.set(this.vms[name], 'loading', true);
    },
    _tableUnLoading(name){
      _.set(this.vms[name], 'loading', false);
    },
    _resetForm(name){
      this.vms[name].resetFields();
    }
  },
};
